package com.it.schoolbookshop_back.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.entities.po.Book;
import com.it.schoolbookshop_back.entities.po.User;
import com.it.schoolbookshop_back.entities.dto.BookResponseDTO;
import com.it.schoolbookshop_back.entities.dto.FavoriteRequestDTO;
import com.it.schoolbookshop_back.entities.dto.BookAddDTO;
import com.it.schoolbookshop_back.entities.dto.BookEditDTO;
import com.it.schoolbookshop_back.entities.dto.SoldBookDTO;
import com.it.schoolbookshop_back.service.BookService;
import com.it.schoolbookshop_back.service.FavoriteService;
import com.it.schoolbookshop_back.service.UserService;
import com.it.schoolbookshop_back.service.NotificationService;
import com.it.schoolbookshop_back.service.FavoriteService.FavoriteToggleResult;
import com.it.schoolbookshop_back.enums.BookConditionEnum;
import com.it.schoolbookshop_back.enums.BookStatusEnum;
import com.it.schoolbookshop_back.enums.NotificationType;
import com.it.schoolbookshop_back.enums.PriceRangeEnum;
import com.it.schoolbookshop_back.enums.SortByEnum;
import com.it.schoolbookshop_back.utils.UserContext;
import com.it.schoolbookshop_back.utils.Code;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Base64;

import java.util.ArrayList;


@RestController
@RequestMapping("/api/user")
@CrossOrigin
@Slf4j
public class BookController {
    @Autowired
    private BookService bookService;
    
    @Autowired
    private FavoriteService favoriteService;
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private UserService userService;

    /**
     * 查看所有书籍
     * 支持按价格区间、品相过滤，并可指定排序方式
     * 只返回status为active的书籍
     * 该接口无需认证，可以直接访问（已加入拦截器白名单）
     * 
     * 所有参数均为可选，前端不传的参数则不计入排序和筛选
     * @return 书籍列表
     */
    @GetMapping("/book")
    public Result<List<BookResponseDTO>> getBooks(
            @RequestParam(value = "price_range", required = false) PriceRangeEnum priceRange,
            @RequestParam(value = "book_condition", required = false) BookConditionEnum bookCondition,
            @RequestParam(value = "sort", required = false) SortByEnum sort) {
        // 打印接收到的参数详细信息
        System.out.println("\n============== 书籍查询接口被调用 ==============");
        System.out.println("原始请求参数：priceRange=" + priceRange + ", bookCondition=" + bookCondition + ", sort=" + sort);
        
        // 判断参数是否存在
        boolean hasPriceRange = priceRange != null;
        boolean hasBookCondition = bookCondition != null;
        boolean hasSort = sort != null;
        
        System.out.println("参数检查：hasPriceRange=" + hasPriceRange + 
                           ", hasBookCondition=" + hasBookCondition + 
                           ", hasSort=" + hasSort);
        
        // 调用服务层获取书籍列表（包含卖家信息）
        List<BookResponseDTO> books = bookService.getBooksWithSeller(priceRange, bookCondition, sort);
        
        // 手动再次过滤 - 用于调试，确保过滤条件生效
        if (hasPriceRange) {
            double minPrice = 0.0;
            double maxPrice = Double.MAX_VALUE;
            
            switch (priceRange) {
                case BELOW_20:
                    maxPrice = 20.0;
                    break;
                case RANGE_20_50:
                    minPrice = 20.0;
                    maxPrice = 50.0;
                    break;
                case RANGE_50_100:
                    minPrice = 50.0;
                    maxPrice = 100.0;
                    break;
                case ABOVE_100:
                    minPrice = 100.0;
                    break;
            }
            
            final double finalMinPrice = minPrice;
            final double finalMaxPrice = maxPrice;
            
            System.out.println("手动价格过滤：" + minPrice + " - " + maxPrice);
            
            List<BookResponseDTO> filteredByPrice = books.stream()
                    .filter(book -> {
                        double price = book.getPrice().doubleValue();
                        boolean matches = price >= finalMinPrice && (finalMaxPrice == Double.MAX_VALUE || price <= finalMaxPrice);
                        System.out.println("书本 " + book.getId() + " - " + book.getTitle() + 
                                           "，价格 " + price + " " + (matches ? "符合" : "不符合") + 
                                           " 价格区间 [" + finalMinPrice + " - " + finalMaxPrice + "]");
                        return matches;
                    })
                    .collect(Collectors.toList());
            
            System.out.println("价格过滤前：" + books.size() + " 本，过滤后：" + filteredByPrice.size() + " 本");
            books = filteredByPrice;
        }
        
        if (hasBookCondition) {
            String targetCondition = null;
            switch (bookCondition) {
                case NEW: targetCondition = "new"; break;
                case GOOD: targetCondition = "good"; break;
                case USED: targetCondition = "used"; break;
            }
            
            final String finalTargetCondition = targetCondition;
            
            System.out.println("手动品相过滤：" + targetCondition);
            
            List<BookResponseDTO> filteredByCondition = books.stream()
                    .filter(book -> {
                        boolean matches = finalTargetCondition.equals(book.getBookCondition());
                        System.out.println("书本 " + book.getId() + " - " + book.getTitle() + 
                                           "，品相 " + book.getBookCondition() + " " + 
                                           (matches ? "符合" : "不符合") + " 目标品相 " + finalTargetCondition);
                        return matches;
                    })
                    .collect(Collectors.toList());
            
            System.out.println("品相过滤前：" + books.size() + " 本，过滤后：" + filteredByCondition.size() + " 本");
            books = filteredByCondition;
        }
        
        // 只返回status为active的书籍 (备用过滤，实际应该由SQL处理)
        books = books.stream()
                .filter(book -> "active".equals(book.getStatus()))
                .collect(Collectors.toList());
        
        System.out.println("最终返回书籍数量: " + books.size());
        for (BookResponseDTO book : books) {
            System.out.println("- " + book.getId() + ": " + book.getTitle() + 
                              ", 价格: " + book.getPrice() + 
                              ", 品相: " + book.getBookCondition() +
                              ", 卖家: " + book.getSellerName() +
                              ", 院系: " + book.getDepartment());
        }
        System.out.println("============== 书籍查询接口调用结束 ==============\n");
                
        return Result.success("获取书籍列表成功", books);
    }

    /**
     * 收藏或取消收藏书籍
     * 用户ID从token中获取，书籍ID从请求体中获取
     * 根据当前状态自动判断是添加还是取消收藏
     * 
     * @param requestDTO 收藏请求DTO
     * @return 操作结果，包含是否成功以及当前收藏状态
     */
    @PostMapping(value = "/book/favorites")
    public Result<Map<String, Object>> manageFavorite(@RequestBody FavoriteRequestDTO requestDTO) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        // 验证请求参数
        if (requestDTO.getBookId() == null) {
            return Result.validateFailed("书籍ID不能为空");
        }
        
        try {
            // 调用服务切换收藏状态
            FavoriteToggleResult result = favoriteService.toggleFavorite(userId, requestDTO.getBookId());
            
            if (result.isSuccess()) {
                Map<String, Object> data = new HashMap<>();
                data.put("isAdded", result.isAdded());
                data.put("bookId", requestDTO.getBookId());
                data.put("userId", userId);
                
                String message = result.isAdded() ? "收藏成功" : "取消收藏成功";
                System.out.println("用户ID: " + userId + ", 书籍ID: " + requestDTO.getBookId() + ", " + message);
                
                // 如果是添加收藏，则为卖家创建通知
                if (result.isAdded()) {
                    try {
                        // 获取书籍信息，包括卖家ID和书名
                        Book book = bookService.getBookById(requestDTO.getBookId());
                        if (book != null && book.getSellerId() != null) {
                            // 避免自己收藏自己的书也发通知
                            if (!userId.equals(book.getSellerId())) {
                                // 获取用户信息
                                User user = userService.getUserById(userId);
                                String username = user != null ? user.getUsername() : "某用户";
                                
                                // 获取当前创建的收藏记录ID
                                Integer favoriteId = favoriteService.getFavoriteId(userId, requestDTO.getBookId());
                                
                                // 构建通知内容
                                String notificationContent = username + " 收藏了您的书籍《" + book.getTitle() + "》";
                                
                                // 确定relatedId - 优先使用收藏ID，如果为null则使用书籍ID
                                Integer relatedId = favoriteId != null ? favoriteId : book.getId();
                                
                                // 创建通知(无论卖家是否开启了收藏通知，都会保存到数据库)
                                notificationService.createNotification(
                                    book.getSellerId(),
                                    NotificationType.FAVORITE,
                                    notificationContent,
                                    relatedId
                                );
                                
                                log.info("已为卖家(ID:{})创建收藏通知，书籍:{}，关联ID:{}", book.getSellerId(), book.getTitle(), relatedId);
                            }
                        }
                    } catch (Exception e) {
                        // 通知创建失败不影响收藏功能
                        log.error("创建收藏通知失败", e);
                    }
                }
                
                return Result.success(message, data);
            } else {
                return Result.failed(Code.FAVORITE_ERROR, "收藏操作失败");
            }
        } catch (IllegalArgumentException e) {
            // 捕获业务异常，例如书籍不存在
            System.err.println("收藏操作参数错误: " + e.getMessage());
            return Result.failed(Code.PARAMETER_ERROR, e.getMessage());
        } catch (Exception e) {
            // 捕获其他异常
            System.err.println("收藏操作发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.failed(Code.FAVORITE_ERROR, "收藏操作失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户发布的书籍，可根据状态筛选
     * 用户ID从Token中获取
     * 
     * @param status 书籍状态（可以为null，表示查询所有状态）
     * @return 书籍列表
     */
    @GetMapping(value = "/book/my")
    public Result<List<Book>> getMyBooks(@RequestParam(required = false) String status) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        // 检查状态参数是否有效
        if (status != null && !status.isEmpty() && !BookStatusEnum.isValid(status)) {
            return Result.validateFailed("无效的状态值，必须是" + 
                        String.join("、", 
                            java.util.Arrays.stream(BookStatusEnum.values())
                                .map(BookStatusEnum::getValue)
                                .toArray(String[]::new)));
        }
        
        try {
            // 调用服务查询书籍
            List<Book> books = bookService.getBooksBySeller(userId, status);
            
            // 增加日志
            System.out.println("返回用户" + userId + "的" + 
                    (status != null ? BookStatusEnum.fromValue(status).getLabel() : "所有") + 
                    "书籍，共" + books.size() + "本");
            
            return Result.success("获取我的书籍成功", books);
        } catch (Exception e) {
            return Result.failed("获取我的书籍失败: " + e.getMessage());
        }
    }

    /**
     * 获取用户收藏的书籍
     * 用户ID从Token中获取
     * 
     * @return 收藏的书籍列表
     */
    @GetMapping(value = "/book/favorites")
    public Result<List<Book>> getFavoriteBooks() {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 调用服务查询收藏的书籍
            List<Book> books = favoriteService.getFavoriteBooks(userId);
            
            return Result.success("获取收藏书籍成功", books);
        } catch (Exception e) {
            return Result.failed("获取收藏书籍失败: " + e.getMessage());
        }
    }

    /**
     * 上传书籍信息和图片
     * 用户ID从Token中获取
     * 支持同时上传书籍信息和图片信息
     * cover接收前端传来的二进制字节流，cover_type接收图片格式
     * 后端将图片保存到文件系统，并将图片路径存入数据库
     * 注意：不需要上传book_condition，系统会根据new_degree自动判断
     * 
     * @param bookAddDTO 书籍信息（包含cover和cover_type）
     * @return 上传结果
     */
    @PostMapping(value = "/book/upload")
    public Result<Map<String, Object>> uploadBook(@RequestBody BookAddDTO bookAddDTO) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 验证请求参数
            if (bookAddDTO == null) {
                return Result.validateFailed("请求参数不能为空");
            }
            
            // 打印详细参数信息用于调试
            System.out.println("\n============== 书籍上传接口被调用 ==============");
            System.out.println("用户ID: " + userId);
            System.out.println("书籍标题: " + bookAddDTO.getTitle());
            System.out.println("作者: " + bookAddDTO.getAuthor());
            System.out.println("分类: " + bookAddDTO.getCategory());
            System.out.println("价格: " + bookAddDTO.getPrice());
            System.out.println("新旧程度: " + bookAddDTO.getNewDegree());
            System.out.println("描述: " + bookAddDTO.getDescription());
            System.out.println("是否包含图片: " + (bookAddDTO.getCover() != null));
            System.out.println("图片类型: " + bookAddDTO.getCoverType());
            
            // 检查必填字段
            StringBuilder missingFields = new StringBuilder();
            if (bookAddDTO.getTitle() == null || bookAddDTO.getTitle().isEmpty()) {
                missingFields.append("标题不能为空; ");
            }
            if (bookAddDTO.getAuthor() == null || bookAddDTO.getAuthor().isEmpty()) {
                missingFields.append("作者不能为空; ");
            }
            if (bookAddDTO.getCategory() == null || bookAddDTO.getCategory().isEmpty()) {
                missingFields.append("分类不能为空; ");
            }
            if (bookAddDTO.getPrice() == null) {
                missingFields.append("价格不能为空; ");
            }
            if (bookAddDTO.getNewDegree() == null) {
                missingFields.append("新旧程度不能为空; ");
            } else {
                // 根据新旧程度自动设置书籍品相，与BookServiceImpl中的逻辑保持一致
                Integer newDegree = bookAddDTO.getNewDegree();
                if (newDegree < 0 || newDegree > 100) {
                    missingFields.append("新旧程度必须在0-100之间; ");
                } else {
                    // 根据新旧程度设置书籍品相，与BookServiceImpl中的逻辑保持一致
                    if (newDegree >= 90) {
                        bookAddDTO.setBookCondition("new");
                        System.out.println("根据新旧程度(" + newDegree + ")自动设置品相为: 几乎全新(new)");
                    } else if (newDegree >= 60) {
                        bookAddDTO.setBookCondition("good");
                        System.out.println("根据新旧程度(" + newDegree + ")自动设置品相为: 品相良好(good)");
                    } else {
                        bookAddDTO.setBookCondition("used");
                        System.out.println("根据新旧程度(" + newDegree + ")自动设置品相为: 有使用痕迹(used)");
                    }
                }
            }
            if (bookAddDTO.getDescription() == null || bookAddDTO.getDescription().isEmpty()) {
                missingFields.append("描述不能为空; ");
            }
            
            if (missingFields.length() > 0) {
                String errorMsg = "请求参数不完整: " + missingFields.toString();
                System.out.println(errorMsg);
                return Result.validateFailed(errorMsg);
            }
            
            System.out.println("开始上传书籍: 标题=" + bookAddDTO.getTitle() + 
                              ", 作者=" + bookAddDTO.getAuthor() + 
                              ", 品相=" + bookAddDTO.getBookCondition() +
                              ", 是否包含图片=" + (bookAddDTO.getCover() != null));
            
            // 调用服务添加书籍（包含图片信息，现在会保存到文件系统而不是数据库）
            Integer bookId = bookService.addBook(bookAddDTO, userId);
            
            if (bookId != null) {
                Map<String, Object> data = new HashMap<>();
                data.put("bookId", bookId);
                
                System.out.println("书籍上传成功, ID: " + bookId);
                System.out.println("============== 书籍上传接口调用结束 ==============\n");
                return Result.success("上传书籍成功", data);
            } else {
                System.out.println("书籍上传失败: bookId为null");
                System.out.println("============== 书籍上传接口调用结束 ==============\n");
                return Result.failed("上传书籍失败");
            }
        } catch (IllegalArgumentException e) {
            // 捕获参数验证异常
            System.out.println("参数验证异常: " + e.getMessage());
            System.out.println("============== 书籍上传接口调用结束 ==============\n");
            return Result.validateFailed(e.getMessage());
        } catch (Exception e) {
            // 捕获其他异常
            System.err.println("上传书籍失败: " + e.getMessage());
            e.printStackTrace();
            System.out.println("============== 书籍上传接口调用结束 ==============\n");
            return Result.failed("上传书籍失败: " + e.getMessage());
        }
    }


    /**
     * 获取书籍推荐
     * 根据指定书籍ID，查找同类别或同作者的书籍
     * 如不指定书籍ID，则返回空列表
     * 
     * @param bookId 参考书籍ID
     * @return 推荐书籍列表
     */
    @GetMapping(value = "/book/recommend")
    public Result<List<Map<String, Object>>> getRecommendBooks(@RequestParam(value = "book_id", required = false) Integer bookId) {
        try {
            // 如果未提供书籍ID，则返回空列表
            if (bookId == null) {
                return Result.success("获取推荐书籍成功", new ArrayList<>());
            }
            
            // 调用服务获取推荐书籍
            List<BookResponseDTO> books = bookService.getRecommendBooks(bookId);
            
            // 简化返回数据，只包含必要信息
            List<Map<String, Object>> simplifiedBooks = books.stream()
                .map(book -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", book.getId());
                    map.put("title", book.getTitle());
                    map.put("price", book.getPrice());
                    // 构建完整URL
                    String coverPath = book.getCover();
                    if (coverPath != null && !coverPath.isEmpty()) {
                        map.put("cover", "http://localhost:8080/" + coverPath);
                    } else {
                        map.put("cover", coverPath);
                    }
                    map.put("cover_type", book.getCoverType());
                    return map;
                })
                .collect(Collectors.toList());
            
            return Result.success("获取推荐书籍成功", simplifiedBooks);
        } catch (IllegalArgumentException e) {
            // 捕获参数验证异常
            return Result.validateFailed(e.getMessage());
        } catch (Exception e) {
            // 捕获其他异常
            return Result.failed("获取推荐书籍失败: " + e.getMessage());
        }
    }

    @GetMapping("/user_favorite")
    public Result<?> getUserFavoriteBooks(@RequestParam(defaultValue = "1") Integer pageNum,
                                          @RequestParam(defaultValue = "10") Integer pageSize) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        System.out.println("获取用户收藏: userId=" + userId);
        try {
            // 由于BookService接口中没有getUserFavoriteBooks方法，需要使用现有方法
            List<Book> books = favoriteService.getFavoriteBooks(userId);
            
            // 手动实现分页
            int total = books.size();
            int startIndex = (pageNum - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            
            List<Book> pageData = startIndex < endIndex ? 
                                 books.subList(startIndex, endIndex) : 
                                 new ArrayList<>();
            
            // 创建分页结果
            PageInfo<Book> pageInfo = new PageInfo<>(pageData);
            pageInfo.setTotal(total);
            pageInfo.setPageNum(pageNum);
            pageInfo.setPageSize(pageSize);
            
            return Result.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed(Code.GET_ERR, "获取用户收藏图书失败: " + e.getMessage());
        }
    }

    /**
     * 获取单本书籍详情
     * 获取到图书信息的时候，如果cover和cover_type存在则替换返回true，反之则为false
     * 需要和categories表联查才能得到分类的名字category
     * 需要和user表联查才能得到卖家名字seller_name
     * 
     * @param bookId 书籍ID
     * @return 书籍详细信息
     */
    @GetMapping("/book/{book_id}")
    public Result<BookResponseDTO> getBookDetail(@PathVariable("book_id") Integer bookId) {
        try {
            System.out.println("请求获取书籍详情: bookId=" + bookId);
            
            // 调用服务获取书籍详情(包含卖家和分类信息)
            BookResponseDTO bookDetail = bookService.getBookDetailById(bookId);
            
            if (bookDetail == null) {
                return Result.failed(Code.BOOK_NOT_EXIST, "书籍不存在");
            }
            
            // 返回结果
            return Result.success("获取书籍详情成功", bookDetail);
        } catch (IllegalArgumentException e) {
            // 捕获参数验证异常，例如书籍不存在
            System.err.println("获取书籍详情参数错误: " + e.getMessage());
            return Result.failed(Code.PARAMETER_ERROR, e.getMessage());
        } catch (Exception e) {
            // 捕获其他异常
            System.err.println("获取书籍详情发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.failed(Code.GET_ERR, "获取书籍详情失败: " + e.getMessage());
        }
    }

    /**
     * 下架单本书籍
     * 将图书状态修改为REMOVED，而不是删除图书记录
     * 只有书籍的发布者才能下架该书籍
     * 
     * @param bookId 书籍ID
     * @return 操作结果
     */
    @PutMapping("/book/removed/{book_id}")
    public Result<?> removeBook(@PathVariable("book_id") Integer bookId) {
        try {
            System.out.println("请求下架书籍: bookId=" + bookId);
            
            // 从Token中获取用户ID
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.unauthorized();
            }
            
            // 检查书籍是否存在
            Book book = bookService.getBookById(bookId);
            if (book == null) {
                return Result.failed(Code.BOOK_NOT_EXIST, "书籍不存在");
            }
            
            // 验证当前用户是否为书籍发布者
            if (!userId.equals(book.getSellerId())) {
                return Result.failed(403, "您没有权限下架该书籍，只有书籍发布者才能下架");
            }
            
            // 检查当前状态是否允许下架
            if ("removed".equals(book.getStatus())) {
                return Result.failed(Code.PARAMETER_ERROR, "该书籍已经是下架状态");
            }
            
            // 修改书籍状态为removed
            boolean success = bookService.updateBookStatus(bookId, "removed");
            
            if (success) {
                return Result.success("书籍下架成功", null);
            } else {
                return Result.failed(Code.UPDATE_ERR, "书籍下架失败");
            }
        } catch (Exception e) {
            // 捕获其他异常
            System.err.println("下架书籍发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.failed(Code.UPDATE_ERR, "下架书籍失败: " + e.getMessage());
        }
    }

    /**
     * 增加书籍浏览次数
     * 用户ID从token中获取
     * 用户同一时间内重复浏览同一本书浏览次数不会增加，除非时间过期，缓存时间十分钟
     * 
     * @param bookId 书籍ID
     * @return 操作结果
     */
    @PutMapping("/book/addViews/{book_id}")
    public Result<?> addBookViews(@PathVariable("book_id") Integer bookId) {
        try {
            System.out.println("请求增加书籍浏览次数: bookId=" + bookId);
            
            // 从Token中获取用户ID
            Integer userId = UserContext.getUserId();
            if (userId == null) {
                return Result.unauthorized();
            }
            
            // 检查书籍是否存在
            Book book = bookService.getBookById(bookId);
            if (book == null) {
                return Result.failed(Code.BOOK_NOT_EXIST, "书籍不存在");
            }
            
            // 增加浏览次数
            boolean success = bookService.incrementBookViews(bookId, userId);
            
            if (success) {
                return Result.success("增加浏览次数成功", null);
            } else {
                return Result.failed(Code.UPDATE_ERR, "增加浏览次数失败");
            }
        } catch (IllegalArgumentException e) {
            // 捕获参数验证异常
            System.err.println("增加浏览次数参数错误: " + e.getMessage());
            return Result.failed(Code.PARAMETER_ERROR, e.getMessage());
        } catch (Exception e) {
            // 捕获其他异常
            System.err.println("增加浏览次数发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.failed(Code.UPDATE_ERR, "增加浏览次数失败: " + e.getMessage());
        }
    }

    /**
     * 获取图书封面
     * 根据book_id查询图书图片，然后返回cover路径和cover_type
     * 
     * @param bookId 书籍ID
     * @return 包含封面图片路径和类型的结果
     */
    @GetMapping("/book/cover/{book_id}")
    public Result<Map<String, String>> getBookCover(@PathVariable("book_id") Integer bookId) {
        try {
            System.out.println("请求获取图书封面: bookId=" + bookId);
            
            // 查询书籍信息
            Book book = bookService.getBookById(bookId);
            if (book == null) {
                return Result.failed(Code.BOOK_NOT_EXIST, "书籍不存在");
            }
            
            // 检查书籍是否有封面信息
            if (book.getCover() == null || book.getCoverType() == null) {
                return Result.failed(Code.PARAMETER_ERROR, "书籍没有封面图片");
            }
            
            // 构造返回数据
            Map<String, String> coverData = new HashMap<>();
            
            try {
                // 获取存储的图片路径 - 已经是字符串，无需转换
                String imagePath = book.getCover();
                
                coverData.put("cover", imagePath);
                coverData.put("cover_type", book.getCoverType());
                
                System.out.println("成功获取图书封面路径: " + imagePath);
                
                return Result.success("获取图书封面成功", coverData);
            } catch (Exception e) {
                System.err.println("处理图书封面路径失败: " + e.getMessage());
                e.printStackTrace();
                return Result.failed(Code.GET_ERR, "获取图书封面路径失败: " + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("获取图书封面时发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.failed(Code.GET_ERR, "获取图书封面失败: " + e.getMessage());
        }
    }

    /**
     * 编辑书籍信息
     * 通过book_id查找书籍并动态修改
     * 只有书籍的发布者才能编辑自己的书籍
     * 
     * @param bookEditDTO 书籍编辑DTO
     * @return 操作结果
     */
    @PostMapping("/book/editBook")
    public Result<?> editBook(@RequestBody BookEditDTO bookEditDTO) {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        // 验证请求参数
        if (bookEditDTO == null || bookEditDTO.getBookId() == null) {
            return Result.validateFailed("书籍ID不能为空");
        }
        
        try {
            // 调用服务编辑书籍
            boolean success = bookService.editBook(bookEditDTO, userId);
            
            if (success) {
                return Result.success("书籍编辑成功");
            } else {
                return Result.failed("书籍编辑失败，可能是因为书籍不存在或者您不是书籍的发布者");
            }
        } catch (IllegalArgumentException e) {
            // 捕获业务异常，例如参数错误
            System.err.println("编辑书籍参数错误: " + e.getMessage());
            return Result.validateFailed(e.getMessage());
        } catch (Exception e) {
            // 捕获其他异常
            System.err.println("编辑书籍发生异常: " + e.getMessage());
            e.printStackTrace();
            return Result.failed("编辑书籍失败: " + e.getMessage());
        }
    }

    /**
     * 查询已购买的书籍
     * 根据token中的用户ID查询已经购买的书籍信息
     * 
     * @return 已购买的书籍信息列表
     */
    @GetMapping("/book/lookBought")
    public Result<Map<String, Object>> lookBoughtBooks() {
        // 从Token中获取用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 调用服务查询已购买书籍
            List<SoldBookDTO> boughtBooks = bookService.getBoughtBooks(userId);
            
            // 构造返回结果
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("books", boughtBooks);
            
            return Result.success("获取已购买书籍成功", resultMap);
        } catch (Exception e) {
            log.error("获取已购买书籍失败: {}", e.getMessage(), e);
            return Result.failed("获取已购买书籍失败: " + e.getMessage());
        }
    }
}
